from flask import request
from flask_restx import Resource
from werkzeug.security import generate_password_hash, check_password_hash
from app.extensions import db
from app.models.user import User
from app.utils.jwt_utils import generate_token, decode_token
from app.protocols import auth_ns, register_model, login_model, response_model


@auth_ns.route('/register')
class Register(Resource):
    @auth_ns.expect(register_model)
    @auth_ns.marshal_with(response_model)
    def post(self):
        """用户注册"""
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')

        # 检查用户名或邮箱是否已存在
        if User.query.filter_by(username=username).first():
            auth_ns.abort(400, message='用户名已存在')

        # 创建新用户
        user = User(
            username=username,
            password=generate_password_hash(password)
        )
        db.session.add(user)
        db.session.commit()

        return {'message': '注册成功'}, 201


@auth_ns.route('/login')
class Login(Resource):
    @auth_ns.expect(login_model)
    @auth_ns.marshal_with(response_model)
    def post(self):
        """用户登录"""
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')

        user = User.query.filter_by(username=username, state=1).first()
        if not user or not check_password_hash(user.password, password):
            auth_ns.abort(401, message='用户名或密码错误')

        token = generate_token(user.id)
        return {
            'message': '登录成功',
            'data': {'token': token}
        }, 200
